package com.zmj.sy.mom.srv.aps.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmj.sy.mom.srv.aps.bean.entity.reportErp.NoreportErpConfig;
import com.zmj.sy.mom.srv.aps.bean.entity.reportErp.ReportErpPartInfo;
import com.zmj.sy.mom.srv.aps.bean.vo.reportErp.*;
import com.zmj.sy.mom.srv.aps.mapper.NoreportErpConfigMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工单不回传配置(NoreportErpConfig)表服务实现类
 *
 * @author hejiahui
 * @since 2025-07-31 11:45:15
 */
@Service("tbMesNoreportErpConfigService")
public class NoreportErpConfigService extends ServiceImpl<NoreportErpConfigMapper, NoreportErpConfig>{

    /**
     * 分页查询
     *
     * @param noreportErpConfigReqVo 筛选条件
     * @return 查询结果
     */
    public IPage<NoreportErpConfigResVo> queryByPage(NoreportErpConfigReqVo noreportErpConfigReqVo) {
        IPage<NoreportErpConfig> page = new Page<>(noreportErpConfigReqVo.getPage(), noreportErpConfigReqVo.getSize());
        QueryWrapper<NoreportErpConfig> query = new QueryWrapper();
        query.eq("deleted", 0);
        query.like(StringUtils.isNotBlank(noreportErpConfigReqVo.getOrderCode()), "order_code", noreportErpConfigReqVo.getOrderCode());
        query.like(StringUtils.isNotBlank(noreportErpConfigReqVo.getWorkOrderCode()), "work_order_code", noreportErpConfigReqVo.getWorkOrderCode());
        query.like(StringUtils.isNotBlank(noreportErpConfigReqVo.getPhase()), "phase", noreportErpConfigReqVo.getPhase());
        query.like(StringUtils.isNotBlank(noreportErpConfigReqVo.getPartName()), "part_name", noreportErpConfigReqVo.getPartName());
        query.like(StringUtils.isNotBlank(noreportErpConfigReqVo.getPlmid()), "plmid", noreportErpConfigReqVo.getPlmid());
        IPage<NoreportErpConfig> pages = this.page(page, query);
        IPage<NoreportErpConfigResVo> ResPages = new Page<>();
        BeanUtils.copyProperties(pages,ResPages);
        List<NoreportErpConfigResVo> records = pages.getRecords().stream().map(e->{
            NoreportErpConfigResVo resVo = new NoreportErpConfigResVo();
            BeanUtils.copyProperties(e,resVo);
            resVo.setCreateDateTime(e.getCreateDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            resVo.setModifyDateTime(e.getModifyDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            return resVo;
        }).collect(Collectors.toList());
        ResPages.setRecords(records);
        return ResPages;
    }
    /**
     * 新增数据
     *
     * @param tbMesNoreportErpConfigReqVo 实例对象
     * @return 实例对象
     */
    public void insert(NoreportErpConfigAddListVo tbMesNoreportErpConfigReqVo) {
        //判断是否已存在
        List<PartInfoVo> partInfoList = tbMesNoreportErpConfigReqVo.getPartInfoList();
        List<String> workOrderCodeList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(partInfoList)) {
            workOrderCodeList = partInfoList.stream().map(e -> e.getWorkOrderCode()).collect(Collectors.toList());
        }
        List<String> phaseList = tbMesNoreportErpConfigReqVo.getPhaseList();
        List<NoreportErpConfig> oldConfigList = this.lambdaQuery()
                .eq(NoreportErpConfig::getOrderCode, tbMesNoreportErpConfigReqVo.getOrderCode())
                .in(ObjectUtils.isNotEmpty(workOrderCodeList),NoreportErpConfig::getWorkOrderCode, workOrderCodeList)
                .in(ObjectUtils.isNotEmpty(phaseList),NoreportErpConfig::getPhase, phaseList)
                .list();
        Map<String, List<NoreportErpConfig>> codePhaseMap = new HashMap<>();
        if (ObjectUtils.isNotEmpty(oldConfigList)) {
            codePhaseMap = oldConfigList.stream().collect(Collectors.groupingBy(e -> (StringUtils.isBlank(e.getWorkOrderCode()) ? "" : e.getWorkOrderCode())  + "-" + (StringUtils.isBlank(e.getPhase()) ? "" : e.getPhase())));
        }
        //保存数据
        String errorLog = "";
        NoreportErpConfig target = new NoreportErpConfig();
        BeanUtils.copyProperties(tbMesNoreportErpConfigReqVo,target);
        if (ObjectUtils.isNotEmpty(workOrderCodeList)) {
            for (PartInfoVo workOrderCode : partInfoList) {
                NoreportErpConfig myTarget = new NoreportErpConfig();
                BeanUtils.copyProperties(workOrderCode,myTarget);
                myTarget.setOrderCode(target.getOrderCode());
                if (ObjectUtils.isNotEmpty(phaseList)) {
                    for (String phase : phaseList) {
                        myTarget.setPhase( phase);
                        List<NoreportErpConfig> noreportErpConfigs = codePhaseMap.get( myTarget.getWorkOrderCode() + "-" + myTarget.getPhase());
                        if (ObjectUtils.isEmpty(noreportErpConfigs)) {
                            this.save(myTarget);
                        }else {
                            errorLog = errorLog + "施工号:" + myTarget.getOrderCode() + "工单:" + myTarget.getWorkOrderCode() + " 工序:" + myTarget.getPhase() + " 已存在" + "\n";
                        }
                    }
                }else {
                    List<NoreportErpConfig> noreportErpConfigs = codePhaseMap.get( myTarget.getWorkOrderCode() + "-" + "");
                    if (ObjectUtils.isEmpty(noreportErpConfigs)) {
                        this.save(myTarget);
                    }else {
                        errorLog = errorLog + "施工号:" + myTarget.getOrderCode() + "工单:" + myTarget.getWorkOrderCode() + " 已存在" + "\n";
                    }
                }
            }
        } else if (ObjectUtils.isNotEmpty(phaseList)) {
            for (String phase : phaseList) {
                NoreportErpConfig myTarget = new NoreportErpConfig();
                BeanUtils.copyProperties(target,myTarget);
                myTarget.setPhase( phase);
                List<NoreportErpConfig> noreportErpConfigs = codePhaseMap.get("" + "-" +  myTarget.getPhase());
                if (ObjectUtils.isEmpty(noreportErpConfigs)) {
                    this.save(myTarget);
                }else {
                    errorLog = errorLog + "施工号:" + myTarget.getOrderCode() + " 工序:" + myTarget.getPhase() + " 已存在" + "\n";
                }
            }
        } else {
            List<NoreportErpConfig> noreportErpConfigs = codePhaseMap.get("-");
            if (ObjectUtils.isEmpty(noreportErpConfigs)) {
                this.save(target);
            }else {
                errorLog = errorLog + "施工号:" + tbMesNoreportErpConfigReqVo.getOrderCode() + " 已存在" + "\n";
            }
        }
        if (StringUtils.isNotBlank(errorLog)) {
            throw new RuntimeException(errorLog);
        }
    }

    /**
     * 修改数据
     *
     * @param tbMesNoreportErpConfigReqVo 实例对象
     * @return 实例对象
     */
    public void update(NoreportErpConfigAddVo tbMesNoreportErpConfigReqVo) {
        NoreportErpConfig target = new NoreportErpConfig();
        BeanUtils.copyProperties(tbMesNoreportErpConfigReqVo,target);
        //判断是否已存在
        List<NoreportErpConfig> oldConfigList = this.lambdaQuery()
                .ne(NoreportErpConfig::getId, target.getId())
                .eq(NoreportErpConfig::getOrderCode, target.getOrderCode())
                .eq(StringUtils.isNotBlank(tbMesNoreportErpConfigReqVo.getPlmid()) , NoreportErpConfig::getPlmid, target.getPlmid())
                .eq(StringUtils.isNotBlank(tbMesNoreportErpConfigReqVo.getWorkOrderCode()), NoreportErpConfig::getWorkOrderCode, target.getWorkOrderCode())
                .eq(StringUtils.isNotBlank(tbMesNoreportErpConfigReqVo.getPhase()) , NoreportErpConfig::getPhase, target.getPhase())
                .list();
        if (ObjectUtils.isNotEmpty(oldConfigList)) {
            throw new RuntimeException("已存在");
        }
        this.updateById(target);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public void deleteById(Integer id) {
        baseMapper.deleteById(id);
    }
    /**
     * @Description: 根据施工号获取零件
     *
     * @author: hejiahui
     * @since: 2025/8/1 10:34
     */
    public List<ReportErpPartInfoVo> getWorkOrderCodeByOrder(String orderCode, String plmid) {
        QueryWrapper<?> query = new QueryWrapper();
        query.eq("ord.construct_no", orderCode);
        query.isNotNull("bom.work_order_code");
        query.isNotNull("bom.plm_id");
        query.like(StringUtils.isNotBlank(plmid),"CONCAT(bom.plm_id,bom.work_order_code,bom.mater_name)", plmid);
        List<ReportErpPartInfo> reportErpConfigList = baseMapper.getWorkOrderCodeByOrder(query);
        final List<ReportErpPartInfoVo> voList = reportErpConfigList.stream().map(e -> {
            ReportErpPartInfoVo resVo = new ReportErpPartInfoVo();
            BeanUtils.copyProperties(e, resVo);
            return resVo;
        }).collect(Collectors.toList());
        return voList;
    }

    public List<String> getWorkPhase(String orderCode, String plmid, String phase) {
        QueryWrapper<?> query = new QueryWrapper();
        query.eq("ord.construct_no", orderCode);
        query.eq("bom.plm_id", plmid);
        List<ReportErpPartInfo> reportErpConfigList = baseMapper.getWorkOrderCodeByOrder(query);
        if (ObjectUtils.isEmpty(reportErpConfigList)) {
            return new ArrayList<>();
        }
        List<String> phaseList = Arrays.asList(reportErpConfigList.get(0).getWorkChain().split("-"));
        if (StringUtils.isNotBlank(phase)) {
            phaseList = phaseList.stream().filter(e -> e.contains(phase)).collect(Collectors.toList());
        }
        return phaseList;
    }
    /**
     * @Description: 成品配置查询
     *
     * @author: hejiahui
     * @since: 2025/8/12 17:00
     */
    public List<NoreportErpConfigResVo> queryList(FinishedConfigReqVo finishedConfigReqVo) {
        QueryWrapper<NoreportErpConfig> query = new QueryWrapper();
        query.eq("deleted", 0);
        query.like(StringUtils.isNotBlank(finishedConfigReqVo.getOrderCode()), "order_code", finishedConfigReqVo.getOrderCode());
        query.like(StringUtils.isNotBlank(finishedConfigReqVo.getPhase()), "phase", finishedConfigReqVo.getPhase());
        query.like(StringUtils.isNotBlank(finishedConfigReqVo.getPlmid()), "plmid", finishedConfigReqVo.getPlmid());
        List<NoreportErpConfig> list = this.list(query);
        List<NoreportErpConfigResVo> records = list.stream().map(e->{
            NoreportErpConfigResVo resVo = new NoreportErpConfigResVo();
            BeanUtils.copyProperties(e,resVo);
            resVo.setCreateDateTime(e.getCreateDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            resVo.setModifyDateTime(e.getModifyDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            return resVo;
        }).collect(Collectors.toList());
        return records;
    }
}


